<template>
  <div class="invitee">
    <div class="header">
      <van-nav-bar
        title="超级会员邀请者"
        left-arrow
        @click-left="onClickNavBarLeft"
      />
    </div>
    <div class="tabs">
      <van-tabs v-model="role" @change="onChangeTabs" color="#FFB72F">
        <van-tab title="邀请记录" :name="0"></van-tab>
        <van-tab title="合作中" :name="1"></van-tab>
        <van-tab :name="2">
          <template slot="title">
            <van-badge :dot="isDot">
              <div style="padding: 5px">已退出</div>
            </van-badge>
          </template>
        </van-tab>
      </van-tabs>
    </div>
    <div v-if="loading" class="noInfo loading">
      <img src="../../../assets/img/flow/loading.gif" alt="" width="80px" />
    </div>
    <div class="list" ref="listRef" v-if="list.length > 0 && !loading">
      <div
        class="list-item section-line"
        v-for="(item, index) in list"
        :key="index"
      >
        <div
          style="display: flex"
          v-if="params.cooperate === 0"
          class="list-item-label section-line"
        >
          <div style="color: #F05357;flex: 1">
            <!--            取消合作退出方式：1：本商户取消合作 2：参与者取消合作-->
            {{ item.exitType === 1 ? "本商户取消合作" : "参与者取消合作" }}
          </div>
          <div style="flex: 1;text-align: right;margin-right: 5px">
            {{ item.exitTime }}
          </div>
        </div>

        <div v-if="params.cooperate !== 0 && params.cooperate !== 1">
          <div
            class="list-item-state"
            :style="{
              backgroundColor: STATE_TEXT_COLOR[item.status]
            }"
          >
            {{ STATE_TEXT[item.status] }}
          </div>
          <span
            style="text-align: right;margin-right: 5px"
            v-if="item.status === 3"
          >
            时间到期,未同意，系统自动拒绝
          </span>
        </div>
        <div style="display: flex" class="list-item-label">
          <span style="flex: 1" class="list-item-title">{{
            item.joinBusinessName
          }}</span>
          <span style="flex: 1;text-align: right" class="list-item-phone">{{
            item.joinMobilePhone
          }}</span>
        </div>
        <div class="list-item-label">
          <van-icon :name="financingPartyIcon" />
          <span class="list-item-text"
            >出资方：{{
              item.financingParty === 2 ? "合作商户" : "本商户"
            }}</span
          >
        </div>
        <div class="list-item-label">
          <van-icon :name="denominationIcon" />
          <span class="list-item-text">
            优惠折扣：{{ item.discount }}折
            <span
              v-if="params.cooperate === 1 && item.afterDiscount"
              style="color: #F05357"
              >（新折扣{{ item.afterDiscount }}折）</span
            >
          </span>
        </div>

        <div class="list-item-label">
          <van-icon :name="walletIcon" />
          <span class="list-item-text">
            抽佣比例：{{ item.rakeRate }}%

            <span
              v-if="params.cooperate === 1 && item.afterRakeRate"
              style="color: #F05357"
              >（新比例{{ item.afterRakeRate }}%）</span
            >
          </span>
        </div>
        <div class="list-item-label">
          <van-icon :name="integralIcon" />
          <span class="list-item-text">
            积分奖励：{{ item.rewardCoefficient }}元=1积分</span
          >
        </div>
        <div class="list-item-label">
          <van-icon :name="integralIcon" />
          <span class="list-item-text">
            积分抵扣比例：{{ item.deductionRatio }}%
            <span
              v-if="params.cooperate === 1 && item.afterDeductionRatio"
              style="color: #F05357"
              >（新比例{{ item.afterDeductionRatio }}%）</span
            >
          </span>
        </div>
        <div style="display: flex" class="list-item-label" v-if="role === 1">
          <div style="flex: 1">
            <van-button @click="onClickCancel(item)" plain type="info"
              >取消合作</van-button
            >
          </div>
          <div style="flex: 1;text-align: right">
            <van-button
              @click="onClickEdit(item)"
              class="van-button-edit"
              :disabled="
                item.afterRakeRate ||
                  item.afterDiscount ||
                  item.afterDeductionRatio
              "
              >修改</van-button
            >
          </div>
        </div>
      </div>
    </div>
    <van-empty
      v-if="list.length === 0 && !loading"
      :image="emptyUrl"
      :description="emptyText"
    />
    <div class="footer">
      <van-button @click="onClickToInvitingMerchants">邀请商户</van-button>
    </div>
  </div>
</template>

<script>
import {
  getInviterRecord,
  getInviterCooperationRecords,
  inviterCancelCooperation,
  getInviterRedDot
} from "@/api/flow/index";
import { Dialog } from "vant";
import {
  INVITEE_STATE,
  INVITEE_STATE_TEXT_COLOR
} from "@/views/flow/surperActivity/config";

export default {
  name: "index",
  data() {
    return {
      STATE_TEXT: INVITEE_STATE,
      STATE_TEXT_COLOR: INVITEE_STATE_TEXT_COLOR,
      emptyUrl: require("@/assets/img/empty-data.png"),
      role: 0,
      apis: getInviterRecord,
      hasNextPage: false,
      loading: true,
      isDot: false,
      params: {
        merchantId: 0,
        pageNum: 1,
        pageSize: 10,
        status: "" //状态: 0:待同意, 1:已同意, 2: 已拒绝
      },
      list: [],
      financingPartyIcon: require("@/assets/img/flow/financingParty.png"),
      denominationIcon: require("@/assets/img/flow/denomination.png"),
      walletIcon: require("@/assets/img/flow/wallet.png"),
      integralIcon: require("@/assets/img/flow/integral.png")
    };
  },
  computed: {
    flowQueryData() {
      return this.$store.state.flow.flowQueryData;
    },
    emptyText() {
      const role = this.role;
      return (
        "暂无" +
        (role === 0
          ? "邀请记录"
          : role === 1
          ? "合作商户，快去邀请"
          : "已退出记录")
      );
    }
  },
  created() {
    this.initData();
  },
  mounted() {
    this.$refs.listRef?.addEventListener("scroll", this.nextPage, true);
  },
  updated() {
    this.$refs.listRef?.addEventListener("scroll", this.nextPage, true);
  },
  methods: {
    onChangeTabs() {
      this.loading = true;
      switch (this.role) {
        case 0:
          this.apis = getInviterRecord;
          this.params.pageNum = 1;
          this.params.cooperate = "";
          this.list = [];
          this.initData();
          break;
        case 1:
          this.apis = getInviterCooperationRecords;
          this.params.pageNum = 1;
          this.params.cooperate = 1;
          this.list = [];
          this.initData();
          break;
        case 2:
          this.apis = getInviterCooperationRecords;
          this.params.pageNum = 1;
          this.params.cooperate = 0;
          this.list = [];
          this.initData();
          break;
        default:
          this.apis = getInviterRecord;
          break;
      }
    },
    //取消合作
    onClickCancel({ id }) {
      Dialog({
        title: "提示",
        showCancelButton: true,
        message: "是否取消合作？消后用户在当前商家消费将不享受超级会员优惠"
      }).then(async () => {
        const { data } = await inviterCancelCooperation({
          id,
          merchantId: this.flowQueryData.merchantId
        });
        const { code, msg } = data;
        if (code === 0 && msg === "success") {
          this.$toast.success("成功");
          await this.initData(true);
        } else {
          this.$toast.fail("失败");
        }
      });
    },
    nextPage() {
      if (!this.hasNextPage) return;
      let scrollHeight = this.$refs.listRef.scrollHeight;
      let scrollTop = this.$refs.listRef.scrollTop;
      let clientHeight = this.$refs.listRef.clientHeight;
      if (scrollHeight - clientHeight <= scrollTop) {
        this.params.pageNum++;
        this.initData();
      }
    },
    onClickNavBarLeft() {
      this.$router.go(-1);
    },
    async initData(isClear = false) {
      if (isClear) {
        this.params.pageNum = 1;
        this.list = [];
        this.loading = true;
      }
      const { data } = await this.apis({
        ...this.params,
        merchantId: this.flowQueryData.merchantId
      });
      const { code, msg, data: res } = data;
      if (code === 0 && msg === "success") {
        const { list, hasNextPage } = res;
        this.list = [...this.list, ...list];
        this.hasNextPage = hasNextPage;
      }
      const { data: data2 } = await getInviterRedDot({
        merchantId: this.flowQueryData.merchantId
      });
      const { code: code2, msg: msg2, data: res2 } = data2;
      if (code2 === 0 && msg2 === "success") {
        this.isDot = res2.exitedRedDot;
        setTimeout(() => {
          this.loading = false;
        }, 800);
      } else {
        this.loading = false;
        this.$toast.fail(msg);
      }
    },
    onClickToInvitingMerchants() {
      this.$router.push({
        name: "invitingMerchants",
        query: {
          isAdd: true //true是新增，false是编辑
        }
      });
    },
    onClickEdit(obj) {
      window.localStorage.setItem("invitingMerchantsInfo", JSON.stringify(obj));
      this.$router.push({
        name: "invitingMerchants",
        query: {
          isAdd: false
        }
      });
    }
  }
};
</script>

<style scoped lang="less">
/deep/.van-empty__image {
  width: inherit;
  height: inherit;
}
.section-line {
  position: relative;
  margin: 10px 0;
  &::after {
    position: absolute;
    box-sizing: border-box;
    content: " ";
    pointer-events: none;
    right: 16px;
    bottom: -10px;
    left: 16px;
    border-bottom: 1px solid #ebedf0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
  }
}
.invitee {
  .footer {
    width: 100vw;
    position: fixed;
    bottom: 0;
    background-color: whitesmoke;
    .van-button {
      width: 100%;
      height: 98px;
      border-radius: 0px;
      background: #ffb72f;
      color: white;
    }
  }
  /deep/.van-badge--dot {
    top: 5px;
    right: 10px;
  }
  .list {
    height: 82vh;
    overflow: hidden;
    overflow-y: scroll;
    font-size: 1rem;
    background-color: whitesmoke;
    margin-bottom: 100px;
    &-item {
      width: 95%;
      margin: 20px auto;
      background-color: white;
      box-shadow: 0px 0px 5px 0px rgba(166, 155, 149, 0.12);
      border-radius: 15px;
      padding: 15px 0;
      &-title {
        font-weight: bold;
        display: flex;
        align-items: center;
        font-size: 1rem;
        opacity: 1 !important;
      }
      &-state {
        width: 138px;
        height: 50px;
        color: white;
        line-height: 50px;
        text-align: center;
        border-bottom-right-radius: 9999px;
        border-top-right-radius: 9999px;
        background: #ffb72f;
        font-size: 26px;
        margin-top: 14px;
      }
      &-phone {
        font-size: 28px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #131313;
      }
      &-text {
        font-weight: 500;
        color: #131313;
        opacity: 0.8;
      }
      &-label {
        padding: 5px 30px;
        margin-top: 20px;
        font-size: 26px;
        display: flex;
        align-items: center;
      }
    }
    .van-button {
      width: 200px;
    }
  }
  .noInfo {
    margin-top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.van-button-edit {
  color: white;
  background-color: #ffb72f;
}
.van-button {
  width: 180px;
  height: 76px;
  border-radius: 38px;
}
.van-icon {
  font-size: 1.125rem;
  margin-right: 5px;
}
/deep/.van-tab--active {
  color: #ffb72f !important;
}
</style>
